package com.example.hello.service.impl;

import com.example.hello.mapper.PaymentLogMapper;
import com.example.hello.mapper.UserMapper;
import com.example.hello.pojo.OverdueCount;
import com.example.hello.pojo.PaymentLog;
import com.example.hello.service.PaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
public class PaymentServiceImpl implements PaymentService {

    /** 每本逾期书每天罚款 1 元，可改为从配置读取 */
    private static final BigDecimal OVERDUE_FEE_PER_BOOK_PER_DAY = BigDecimal.valueOf(1);

    @Autowired
    private UserMapper userMapper;
    @Autowired private PaymentLogMapper logMapper;

    @Override
    @Transactional
    public BigDecimal recharge(Long userId, BigDecimal amount) {
        // 1. 读旧余额
        BigDecimal before = userMapper.getAccountMoney(userId);
        BigDecimal after  = before.add(amount);

        // 2. 更新余额
        userMapper.updateAccountMoney(userId, after);

        // 3. 写流水
        PaymentLog log = new PaymentLog();
        log.setUserId(userId);
        log.setBizType(0);
        log.setAmount(amount);
        log.setBalanceBefore(before);
        log.setBalanceAfter(after);
        log.setRemark("充值");
        logMapper.insert(log);

        return after;
    }

    /** 每天 0 点：累加逾期罚金 */
    @Override
    @Scheduled(cron = "0 0 0 * * *")
    @Transactional
    public void accrueOverdue() {
        // 1. 查出所有逾期未还的书数量
        List<OverdueCount> list = userMapper.listOverdueCounts();
        for (OverdueCount oc : list) {
            BigDecimal delta = OVERDUE_FEE_PER_BOOK_PER_DAY.multiply(
                BigDecimal.valueOf(oc.getCount())
            );
            // 2. 更新 overdue_pay 字段
            userMapper.increaseOverduePay(oc.getUserId(), delta);
            // （可选）不插支付流水，因为这只是计费，非用户主动支付
        }
    }

    /** 用户点击“逾期代付款” */
    @Override
    @Transactional
    public void payOverdue(Long userId, BigDecimal amount) {
        // 1. 读余额与欠款
        BigDecimal balance = userMapper.getAccountMoney(userId);
        BigDecimal overdue  = userMapper.getOverduePay(userId);

        if (balance.compareTo(amount) < 0) {
            throw new RuntimeException("余额不足，请先充值");
        }

        // 2. 扣除
        BigDecimal newBalance = balance.subtract(amount);
        BigDecimal newOverdue  = overdue.subtract(amount).max(BigDecimal.ZERO);
        userMapper.updateAccountMoney(userId, newBalance);
        userMapper.payOverdue(userId, amount);

        // 3. 写流水
        PaymentLog log = new PaymentLog();
        log.setUserId(userId);
        log.setBizType(1);
        log.setAmount(amount.negate());
        log.setBalanceBefore(balance);
        log.setBalanceAfter(newBalance);
        log.setRemark("逾期缴费");
        logMapper.insert(log);
    }

    /** 查询流水 */
    @Override
    public List<PaymentLog> getPaymentLogs(Long userId) {
        return logMapper.selectByUserId(userId);
    }
}